<template>
	<view class="qkTabs">
		<view class="tabsMain">
			<template v-for="(item,index) in list">
				<view class="tabsItem" :key="index" :class="[`nav-item-${index}`]" @click="clickHandler(item,index)">
					<text class="title">{{item.name}}</text>
				</view>
			</template>
		</view>
		<view class="navLine"
			:class="[lineOffsetLeft > 0 ? 'show' : 'hide']"
			:style="[{
				width: lineWidth+'px',
				height: lineHeight+'px',
				transform: `translateX(${lineOffsetLeft}px)`,
				transitionDuration: `${isflag ? 0 : duration}ms`,
				backgroundColor: lineColor
			}]"
		/>
	</view>
</template>

<script>
	export default {
		name: 'QkTabs',
		props: {
			// tabs标签数组
			list: {
			    type: Array,
			    default: function() {
					return [];
				}
			},
			// 滑块的移动过渡时间，单位ms
			duration: {
			    type: Number,
			    default: 300
			},
			// 滑块颜色
			lineColor: {
			    type: String,
			    default: '#303133'
			},
			// 滑块长度
			lineWidth: {
			    type: [String, Number],
			    default: 9
			},
			// 滑块高度
			lineHeight: {
			    type: [String, Number],
			    default: 2
			},
			// 当前选中标签的索引
			current: {
				type: [String, Number],
				default: 2
			}
		},
		data() {
			return {
				lineOffsetLeft: 0,
				isflag: true
			}
		},
		mounted() {
			this.init();
		},
		watch: {
			current() {
				this.setLineLeft();
			}
		},
		methods: {
			init() {
				uni.$u.sleep().then(() => {
					this.resize()
				})
			},
			resize() {
				this.list.forEach( (item,index) => {
					this.$uGetRect(`.nav-item-${index}`).then( res => {
						this.list[index].rect = res;
					})
				})
				uni.$u.sleep(100).then( () => {
					this.setLineLeft();
				})
			},
			setLineLeft() {
				const tabItem = this.list[this.current];
				if ( !tabItem ) return false;
				let lineOffsetLeft = this.list
					.slice(0,this.current)
					.reduce((total,item) => {
						return total += item.rect.width;
					},0);
				this.lineOffsetLeft = lineOffsetLeft + (tabItem.rect.width - this.lineWidth) / 2;
				if (this.isflag) {
					setTimeout(() => {
						this.isflag =  false;
					},10)
				}
			},
			clickHandler(item,index) {
				this.$emit('change',{...item,index});
			}
		}
	}
</script>

<style lang="scss" scoped >
.qkTabs {
	.tabsMain {
		display: flex;
		margin-bottom: 16rpx;
		.tabsItem {
			padding: 0 32rpx;
			font-size: 26rpx;
			line-height: 26rpx;
			.title {
				color: #909399;
			}
		}
	}
	.navLine {
		border-radius: 1px 1px 0px 1px;
	}
	.show {
		opacity: 1;
	}
	.hide {
		opacity: 0;
	}
}
</style>
